/**
 * 结果集解析
 */
export default class ResultSet {
    static analysisTheTable(option: any, TABLE: any) {
        // 分析有没有 as 重命名的情况
        let map = new Map();
        let underThe = new Set();
        Object.keys(option.tableStructure).forEach(e => {
            map.set(e, Object.assign(TABLE[e], {}));
            map.get(e).child = [];
            option.tableStructure[e].forEach((ee: any) => {
                map.set(ee, Object.assign(TABLE[ee], {}));
                map.get(e).child.push(map.get(ee));
                underThe.add(ee);
            })
        })

        // 分析字段中是否有重命名
        option.field.forEach((e: any) => {
            if (e.includes(" as ")) {
                e = e.replace(/["'`]/g, "");
                let a = e.split(" as ");
                let b = a[0].split(".");
                map.get(b[0]).table_field = map.get(b[0]).table_field.map((e: any) => {
                    if (e == b[1]) return a[1].trim();
                    return e;
                });
            }
        })

        for (let e of underThe.keys()) {
            map.delete(e);
        }

        for (let e of map.values()) {
            return e;
        }
    }


    static pars(table: any, result: any) {
        if (Array.isArray(result)) {
            let obj: any[] = [];
            let list = {};
            // 遍历结果级
            result.forEach(e => {
                this.getData(table, obj, e, list)
            })
            return obj;
        } else {
            let data = {};
            this.getData(table, data, result)
            return data;
        }
    }


    static getData(table: any, obj: any, tar: any, list?: {}) {
        let a: any = {};
        table.table_field.forEach((field: any) => {
            if (tar[field] != undefined) {
                a[field] = tar[field];
                delete tar[field];
            }
        })

        // @ts-ignore
        if (list[JSON.stringify(a)]) {
            // @ts-ignore
            a = list[JSON.stringify(a)];
        } else {
            obj.push(a);
            // @ts-ignore
            list[JSON.stringify(a)] = a;
        }

        // 转移完成，判断有没有下一级
        if (table.child != undefined) {
            list = {};
            // @ts-ignore
            table.child.forEach(e => {
                if (!a[e.table_name]) {
                    a[e.table_name] = [];
                }
                this.getData(e, a[e.table_name], tar, list);
            })
        }
    }
}